<template>
  <div class="page-container">
    <div class="page-inner-container" style="margin: 0px; padding: 10px 10px;">
      <div class="search-panel">
        <el-form :inline="true" label-width="100">
          <el-form-item label="">
            <el-radio-group v-model="query.outletType" @change="outletTypeChange">
              <el-radio v-for="(item, index) in outletType" :key="index + '_outlet'" :label="item.code">{{ item.codeName }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排口状态">
            <el-select v-model="query.outletNewStatus" multiple clearable placeholder="请选择">
              <el-option
                v-for="item in outletNewStatus"
                :key="item.code"
                :value="item.code"
                :label="item.codeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目部">
            <el-select
              v-model="query.projectDepartmentId"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企业">
            <el-select
              v-model="query.enterpriseId"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethodEnterpriseId"
              :loading="loadingEnterpriseId"
            >
              <el-option
                v-for="item in optionsEnterpriseId"
                :key="item.id"
                :label="item.enterpriseShort"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="控制级别">
            <el-select v-model="query.controlLevel" clearable class="w-100" placeholder="请选择">
              <el-option key="-1" value="" label="全部" />
              <el-option
                v-for="(item) in controlLevel"
                :key="item.code"
                :value="item.code"
                :label="item.codeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="行业类别">
            <el-select v-model="query.industryCategory" clearable class="w-100" placeholder="请选择">
              <el-option key="-1" value="" label="全部" />
              <el-option
                v-for="(item,index) in industryCategory"
                :key="index + '_industry'"
                :value="item.code"
                :label="item.codeName"
              />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button v-loading="exportLoading" type="primary" @click="handleExport">导出</el-button>
        </el-form>
      </div>
      <div class="table-panel">
        <el-table
          v-if="tableHead.length > 0"
          ref="multipleTable"
          v-loading="tableLoading"
          class="grid-data-table"
          height="calc(100vh - 260px)"
          :data="tableData"
          style="width: 100%;"
          :row-class-name="rowClassName"
        >
          <!-- style="overflow-x:scroll; width: 1800px" -->
          <el-table-column fixed="left" align="center" type="index" width="50" />
          <el-table-column fixed="left" align="center" prop="realTimeStr" width="140" label="时间" />
          <el-table-column prop="yhourData" width="100" label="小时数据量(昨日/条)" sortable />
          <el-table-column prop="yfaultAlarmCount" align="center" width="210" label="">
            <template slot="header">
              <span style="color: #F56C6C;">分析仪故障</span>/
              <span style="color: #409EFF;">恒值</span>/
              <span style="color: #E6A23C;">超标</span>/
              <span style="color: #909399;">离线</span><br>
              <span>（昨日时长/小时）</span>
            </template>
            <template slot-scope="{row}">
              <span style="color: #F56C6C;">{{ row.yfaultAlarmCount }} </span>/
              <span style="color: #409EFF;">{{ row.yconstantAlarmCount }} </span>/
              <span style="color: #E6A23C;">{{ row.yaccumulatedAlarmCount }} </span>/
              <span style="color: #909399;">{{ row.yofflineAlarmCount }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="yconstantAlarmCount" width="150" label="昨日恒值时长" />
          <el-table-column prop="yaccumulatedAlarmCount" width="150" label="昨日超标时长" /> -->
          <el-table-column header-align="center" label="排口因子">
            <template v-for="(item,index) in tableHead">
              <el-table-column :key="index" header-align="center" :prop="item.prop" :label="item.label" min-width="110">
                <template slot="header" slot-scope="scope">
                  <span v-html="wrapLabel(scope.column.label)" />
                </template>
                <template slot-scope="scope">
                  <template v-if="index==1">
                    <el-popover
                      placement="top-start"
                      trigger="hover"
                    >
                      <div style="width: 300px;max-height: 300px;overflow: auto;">
                        <div v-if="!title[scope.row.index] || title[scope.row.index].length === 0">
                          <i class="el-icon-loading" /><span style="padding-left: 5px;">加载中...</span>
                        </div>
                        <template v-else>
                          <el-row v-if="typeof title[scope.row.index] === 'object'">
                            <el-col v-for="(label,idx) in title[scope.row.index]" :key="idx" style="margin-bottom: 5px;" :span="24">
                              <!-- {{ label }} -->
                              <span v-html="label" />
                            </el-col>
                          </el-row>
                          <div v-else style="color: #999;">
                            {{ title[scope.row.index] }}
                          </div>
                        </template>
                      </div>
                      <div
                        slot="reference"
                        class="cursor-pointer"
                        @mouseover.self="mouseOver(scope.row)"
                        @click="handleToWarning(scope.row)"
                      >
                        <svg-icon v-if="query.outletType=='e012_01'" icon-class="wasteGas" :class="changeColor(scope.row.outletNewStatus)" />
                        <svg-icon v-else-if="query.outletType=='e012_02'" icon-class="wasteWater" :class="changeColor(scope.row.outletNewStatus)" />
                        <span style="margin-left: 10px">{{ scope.row.outletNameT }}</span>
                      </div>
                    </el-popover>
                  </template>
                  <template v-else-if="index>=2 ">
                    <span style="margin-left: 10px" :class="changeColorByDataStatus(scope.row[item.prop+'_dataStatus'])">{{ scope.row[item.prop] }}</span>
                  </template>
                  <template v-else>
                    <span style="margin-left: 10px">{{ scope.row[item.prop] }}</span>
                  </template>
                </template>
              </el-table-column>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <WarningListDialog
      :dialog-visible="warningDialogVisible"
      :outlet-id="outletId"
      @closeDialog="warningDialogVisible = false"
    />
  </div>
</template>

<script>

import { getDict } from '@/utils/dict'
import { selectOutletRealtimeData, download } from '@/api/dataQuery/realTimeView'
import { getProjectDepartment, getEnterprise, getColorByOutletNewStatus, getColorByDataStatus } from '@/utils/common'
import WarningListDialog from './components/WarningListDialog'
import { getList } from '@/api/business/alarm'
import { downloadFile } from '@/utils'
export default {
  name: 'RealTimeViewPage',
  components: {
    WarningListDialog
  },
  filters: {

  },
  data() {
    return {
      filterText: '',
      query: {
        outletType: 'e012_01',
        outletNewStatus: [], // ['e046_05', 'e046_06', 'e046_03']
        enterpriseId: null,
        projectDepartmentId: null, controlLevel: '', industryCategory: ''
      },
      // 存储是列的属性:列的值
      tableData: [],
      tableHead: [],
      tableLoading: false,
      exportLoading: false,
      controlLevel: [],
      industryCategory: [],
      outletNewStatus: [],
      outletType: [],
      /** 测试搜索选择*/
      options: [],
      loading: false,
      /** 企业搜索选择*/
      optionsEnterpriseId: [],
      loadingEnterpriseId: false,
      outletId: null,
      warningDialogVisible: false,
      title: [],
      tooltipLoading: false,
      beforeIndex: -1
    }
  },
  created() {
    this.controlLevel = getDict('e014')
    this.industryCategory = getDict('e013')
    this.outletNewStatus = getDict('e046')
    this.outletType = getDict('e012')
    this.initData()
  },
  methods: {
    wrapLabel(val) {
      let res = val
      if (res) {
        const index = res.indexOf('（')
        if (index !== -1) {
          res = val.substring(0, index) + '<br/>'
          res += val.substring(index, val.length)
          console.log(res)
        }
      }
      return res
    },
    handleToWarning(row) {
      console.log(row)
      this.outletId = row.outletId
      this.warningDialogVisible = true
    },
    initData() {
      this.tableLoading = true
      this.title = []
      const query = JSON.parse(JSON.stringify(this.query))
      var outletNewStatusVar = ''
      if (query.outletNewStatus != null) {
        for (let i = 0; i < query.outletNewStatus.length; i++) {
          outletNewStatusVar = outletNewStatusVar + query.outletNewStatus[i] + ','
        }
      }
      query.outletNewStatus = outletNewStatusVar
      selectOutletRealtimeData(query).then(res => {
        this.tableData = []
        this.tableHead = []
        console.log(res)
        this.tableHead = res.data.realTimeSumDto.column
        var listRealTimeDto = res.data.realTimeSumDto.listRealTimeDto
        if (listRealTimeDto != null) {
          for (let i = 0; i < listRealTimeDto.length; i++) {
            var temp = listRealTimeDto[i]
            // 计算因子 id
            var factorDtoList = temp.factorDtoList
            if (factorDtoList != null) {
              for (let j = 0; j < factorDtoList.length; j++) {
                temp[factorDtoList[j].factorLibraryIdStr] = factorDtoList[j].val
                temp[factorDtoList[j].factorLibraryIdStr + '_z'] = factorDtoList[j].zsVal
                if (factorDtoList[j].zsVal) {
                  temp[factorDtoList[j].factorLibraryIdStr + '_z_dataStatus'] = factorDtoList[j].dataStatus
                } else {
                  temp[factorDtoList[j].factorLibraryIdStr + '_dataStatus'] = factorDtoList[j].dataStatus
                }
              }
            }
            // 计算排口状态 outletNameT
            temp['outletNameT'] = temp.outletNewStatusName
          }
        }
        this.tableData = listRealTimeDto
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout()
          // el-table加ref="multipleTable"
        })
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleQuery() {
      this.initData()
    },
    handleExport() {
      this.exportLoading = true
      const query = JSON.parse(JSON.stringify(this.query))
      download(query).then(result => {
        downloadFile(result, '设备运行情况统计', 'xlsx')
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        var temp = {}
        temp['queryField'] = query
        getProjectDepartment(temp).then(data => {
          this.options = data.data.list
          this.loading = false
        })
      } else {
        this.options = []
      }
    },
    remoteMethodEnterpriseId(query) {
      if (query !== '') {
        this.loadingEnterpriseId = true
        var temp = {}
        temp['queryField'] = query
        getEnterprise(temp).then(data => {
          this.optionsEnterpriseId = data.data.list
          this.loadingEnterpriseId = false
        })
      } else {
        this.optionsEnterpriseId = []
      }
    },
    outletTypeChange() {
      this.initData()
    },
    changeColor(outletNewStatus) {
      return getColorByOutletNewStatus(outletNewStatus)
    },
    changeColorByDataStatus(status) {
      return getColorByDataStatus(status)
    },
    rowClassName({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    mouseOver(row) {
      if (row.index === this.beforeIndex) {
        return
      }
      this.beforeIndex = row.index
      if (this.title[row.index]) { // 有值的时候就直接显示，不去请求
        return
      }
      var alarmType = ''
      if (row.outletNewStatus === 'e046_05') { // 数据超标
        alarmType = 'e001_03'
      } else if (row.outletNewStatus === 'e046_06') { // 恒值
        alarmType = 'e001_04'
      } else if (row.outletNewStatus === 'e046_01') { // 停运
        alarmType = ''
      } else if (row.outletNewStatus === 'e046_02') { // 停产
        alarmType = ''
      } else if (row.outletNewStatus === 'e046_03') { // 离线
        alarmType = 'e001_01'
      } else if (row.outletNewStatus === 'e046_04') { // 故障
        alarmType = 'e001_02'
      } else { // 正常
        alarmType = ''
      }
      if (alarmType !== '') {
        getList({ outletId: row.outletId, alarmType: alarmType }).then(res => {
          var titleList = []
          if (alarmType === 'e001_03') {
            res.data.rows.forEach(item => {
              const { alarmInformationObj } = item
              const alarmFactor = alarmInformationObj.alarmFactor || ''
              const alarmVal = alarmInformationObj.alarmVal || ''
              const lowerAlarmLimit = alarmInformationObj.lowerAlarmLimit || '0'
              const upperAlarmLimit = alarmInformationObj.upperAlarmLimit || '0'
              if (alarmFactor && alarmVal) {
                const label = alarmFactor + ': ' + alarmVal
                let desc = ''
                if (lowerAlarmLimit && upperAlarmLimit) {
                  desc = `(${lowerAlarmLimit},${upperAlarmLimit})`
                }
                const alarmStartTime = alarmInformationObj.alarmStartTime || ''
                titleList.push(label + desc + '<span style="float: right;">' + alarmStartTime + '</span>')
              }
            })
          } else if (alarmType === 'e001_01') {
            res.data.rows.forEach(item => {
              const alarmVal = item.alarmTypeVal || ''
              const alarmStartTime = item.alarmStartTime || ''
              titleList.push('<span style="color: red;margin-left: 5px;">' + alarmVal + '</span>' + '<span style="float: right;">' + alarmStartTime + '</span>')
            })
          } else {
            res.data.rows.forEach(item => {
              const { alarmInformationObj } = item
              const alarmFactor = alarmInformationObj.alarmFactor || ''
              const alarmVal = item.alarmTypeVal || ''
              const alarmStartTime = item.alarmStartTime || ''
              if (alarmFactor) {
                titleList.push(alarmVal + ': ' + '<span style="color: red;margin-left: 5px;">' + alarmFactor + '</span>' + '<span style="float: right;">' + alarmStartTime + '</span>')
              }
            })
          }
          if (titleList.length === 0) titleList = '暂无内容'
          this.$set(this.title, row.index, titleList)
        }).catch(() => {
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
